package Leetcode第二期;

import java.util.*;

/**
 * @author : K k
 * @date : 18:26 2020/10/18
 */
public class 二叉树的右视图_199 {
    List<Integer> res=new ArrayList<>();

    //BFS
    public List<Integer> rightSideView(TreeNode root) {
        if (root==null){
            return res;
        }
        LinkedList<TreeNode> queue=new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()){
            int size=queue.size();
            res.add(queue.peek().val);
            while (size>0){
                //每一层最右边 为右视图可以看到的元素
                TreeNode node = queue.pollLast();
                if (node.left!=null){
                    queue.addFirst(node.left);
                }
                if (node.right!=null) {
                    queue.addFirst(node.right);
                }
                size--;
            }
        }
        return res;
    }

    //DFS
    public List<Integer> rightSideViewA(TreeNode root) {
        dfs(root,0);
        return res;
    }

    private void dfs(TreeNode root, int depth) {
        if (root==null){
            return;
        }
        if (depth==res.size()){
            res.add(root.val);
        }
        depth++;
        dfs(root.right,depth+1);
        dfs(root.left,depth+1);
    }


    public static void main(String[] args) {
        TreeNode root=new TreeNode(1);
        root.left=new TreeNode(2);
        root.right=new TreeNode(3);
        root.left.right=new TreeNode(5);
        root.right.right=new TreeNode(4);
        二叉树的右视图_199 x=new 二叉树的右视图_199();
        System.out.println(x.rightSideView(root));
    }
}
